<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Tuolaji <479923197@qq.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class ShopController extends AdminbaseController {
    
	protected $shop_model;
	protected $shopcat_model;
	protected $study_model;
	protected $studycat_model;
	protected $shop_size;

	function _initialize() {
		parent::_initialize();
		$this->shop_model = D("Common/Shop");
		$this->shopcat_model = D("Common/ShopCat");
		$this->study_model = D("Common/Study");
		$this->studycat_model = D("Common/StudyCat");
        $this->shop_size = D("Common/ShopSize");
	}
	
	// 后台文章管理列表
	public function index(){
        $study_id=I('request.study_id',0,'intval');
        $studycat_id=I('request.studycat_id',0,'intval');
        $shop_cat_id=I('request.shop_cat_id',0,'intval');
        if(!empty($study_id)){
            $where['s.study_id'] = $study_id;
        }
        if(!empty($shop_cat_id)){
            $where['s.shop_cat_id'] = $shop_cat_id;
        }
        if(!empty($studycat_id)){
            $where['s.studycat_id'] = $studycat_id;
        }
        $start_time=I('request.start_time');
        if(!empty($start_time)){
            $where['shop_date']=array(
                array('EGT',$start_time)
            );
        }

        $end_time=I('request.end_time');
        if(!empty($end_time)){
            if(empty($where['shop_date'])){
                $where['shop_date']=array();
            }
            array_push($where['shop_date'], array('ELT',$end_time));
        }
        $shop_title = I('request.shop_title');
        if(!empty($shop_title)){
            $where['shop_title']=array('like',"%$shop_title%");
        }

        $count=$this->shop_model->count();

        $page = $this->page($count, 6);

        $this->shop_model
            ->alias("s")
            ->join("__USERS__ c ON s.shop_author = c.id")
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->order("s.shop_date DESC");
        if(empty($cid)){
            $this->shop_model->field('s.*,c.user_login,c.user_nicename');
        }else{
            $this->shop_model->field('s.*,c.user_login,c.user_nicename');
        }
        $shops=$this->shop_model->order('s.listorder asc')->select();
        foreach ($shops as $k => $v){
            $shops[$k]['cat_name'] = $this->shopcat_model->where(array('cid'=>$v['shop_cat_id']))->getField('cat_name');
        }
        $p = I('p') == '' ? 1 : I('p');
        $this->assign("page", $page->show('Admin'));
        $this->assign("p", $p);
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->assign("shops",$shops);
        //获取学校
        $study = $this->study_model->where(array('study_status'=>1))->select();
        $this->assign('study',$study);

        //获取商品分类
        $cat = $this->shopcat_model->where(array('cat_status'=>1))->select();
        $this->assign('cat',arr2tree($cat));
        //获取学校分类
        $studycat = $this->studycat_model->where(array('cat_status'=>1))->select();
        $this->assign('studycat',$studycat);
        $this->assign('studycat_id',$studycat_id);
        $this->assign('study_id',$study_id);
        $this->assign('shop_cat_id',$shop_cat_id);
		$this->display();
	}
	
	// 文章添加
	public function add(){
	    /*$a = "{\"1\":{\"size_id\":\"1\",\"kc\":\"4\",\"price\":\"10\"},\"5\":{\"size_id\":\"5\",\"kc\":\"5\",\"price\":\"10\"},\"6\":{\"size_id\":\"6\",\"kc\":\"0\",\"price\":\"0\"},\"7\":{\"kc\":\"0\",\"price\":\"0\"}}";
	    $b = json_decode($a,true);
	    foreach ($b as $k => $v){
	        $b[$k] = array_filter($v);
        }

	    dump(array_filter($b));
	    die;*/
        //获取学校
        $study = $this->study_model->where(array('study_status'=>1))->select();

        //获取分类
        $cat = $this->shopcat_model->where(array('cat_status'=>1,'parentid'=>0))->select();
        foreach ($cat as $k => $v){
           $cat[$k]['f'] = $this->shopcat_model->where(array('cat_status'=>1,'parentid'=>$v['cid']))->select();
        }
        $this->assign('cat',$cat);
        //获取尺寸
        $shop_size = $this->shop_size->where(array('cat_status'=>1))->select();
        $this->assign('study',$study);
        $this->assign('shop_size',$shop_size);
		$this->display();
	}
	
	// 文章添加提交
	public function add_post(){
		if (IS_POST) {
            if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){
                foreach ($_POST['photos_url'] as $key=>$url){
                    $photourl=sp_asset_relative_url($url);
                    $_POST['smeta']['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
                }
            }
			$_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
			$_POST['post']['shop_modified']=date("Y-m-d H:i:s",time());
			$_POST['post']['shop_author']=get_current_admin_id();
			$article=I("post.post");
            $article['smeta']=json_encode($_POST['smeta']);
            foreach ($_POST['shop_size'] as $k => $v){
                $_POST['shop_size'][$k] = array_filter($v);
                if($v['kc'] != null){
                    $_POST['shop_size'][$k]['size_name'] = $this->shop_size->where(array('size_id'=>$v['size_id']))->getField('size_name');
                }
            }
            $article['shop_size'] = json_encode(array_filter($_POST['shop_size']));
            if($_POST['post']['study_id']){
                $article['studycat_id'] = $this->study_model->where(array('study_id'=>$_POST['post']['study_id']))->getField('study_cid');
            }
			$article['shop_content'] = htmlspecialchars_decode($article['shop_content']);
			$result=$this->shop_model->add($article);
			if ($result) {
				$this->success("添加成功！");
			} else {
				$this->error("添加失败！");
			}
		}
	}
	
	// 文章编辑
	public function edit(){
		$id=  I("get.id",0,'intval');
		$shop = $this->shop_model->where("id=$id")->find();
        //获取学校
        $study = $this->study_model->where(array('study_status'=>1))->select();
        //获取分类
        $cat = $this->shopcat_model->where(array('cat_status'=>1,'parentid'=>0))->select();
        foreach ($cat as $k => $v){
            $cat[$k]['f'] = $this->shopcat_model->where(array('cat_status'=>1,'parentid'=>$v['cid']))->select();
        }
        $this->assign('cat',$cat);
        //获取尺寸
        $shop_size = $this->shop_size->where(array('cat_status'=>1))->select();
        $this->assign('study',$study);
        $this->assign('shop_sizes',$shop_size);
        $this->assign("smeta",json_decode($shop['smeta'],true));
        $size = json_decode($shop['shop_size'],true);
        $this->assign("size",$size);
        $p = I('p') == '' ? 1 : I('p');
		$this->assign("shop",$shop);
        $this->assign('p',$p);
		$this->display();
	}
	
	// 文章编辑提交
	public function edit_post(){
		if (IS_POST) {
            if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){
                foreach ($_POST['photos_url'] as $key=>$url){
                    $photourl=sp_asset_relative_url($url);
                    $_POST['smeta']['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
                }
            }
            $_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            $_POST['post']['shop_modified']=date("Y-m-d H:i:s",time());
			unset($_POST['post']['news_author']);
			$article=I("post.post");
            $article['smeta']=json_encode($_POST['smeta']);
            foreach ($_POST['shop_size'] as $k => $v){
                $_POST['shop_size'][$k] = array_filter($v);
                if($v['kc'] != null){
                    $_POST['shop_size'][$k]['size_name'] = $this->shop_size->where(array('size_id'=>$v['size_id']))->getField('size_name');
                }
            }
            $article['shop_size'] = json_encode(array_filter($_POST['shop_size']));
            if($_POST['post']['study_id']){
                $article['studycat_id'] = $this->study_model->where(array('study_id'=>$_POST['post']['study_id']))->getField('study_cid');
            }
            $article['shop_content']=htmlspecialchars_decode($article['shop_content']);
			$result=$this->shop_model->save($article);
			if ($result!==false) {
				$this->success("保存成功！");
			} else {
				$this->error("保存失败！");
			}
		}
	}
	
	// 文章排序
	public function listorders() {
		$status = parent::_listorders($this->shop_model);
		if ($status) {
			$this->success("排序更新成功！");
		} else {
			$this->error("排序更新失败！");
		}
	}

	// 文章删除
	public function delete(){
		if(isset($_GET['id'])){
			$id = I("get.id",0,'intval');
			if ($this->shop_model->where(array('id'=>$id))->delete() !==false) {
				$this->success("删除成功！");
			} else {
				$this->error("删除失败！");
			}
		}
		
		if(isset($_POST['ids'])){
			$ids = I('post.ids/a');
			
			if ($this->shop_model->where(array('id'=>array('in',$ids)))->delete()!==false) {
				$this->success("删除成功！");
			} else {
				$this->error("删除失败！");
			}
		}
	}

    // 下架
    public function ban(){
        $id = I('get.id',0,'intval');
        if ($id) {
            $rst = $this->shop_model->where(array('id'=>$id))->save(array('shop_status'=>0));
            if ($rst) {
                $this->success("商品下架成功！");
            } else {
                $this->error('商品下架失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }

    // 上架
    public function cancelban(){
        $id = I('get.id',0,'intval');
        if ($id) {
            $result = $this->shop_model->where(array('id'=>$id))->save(array('shop_status'=>1));
            if ($result) {
                $this->success("商品上架成功！");
            } else {
                $this->error('商品上架失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }

    /**
     *
     * Enter 导出excel共同方法 ...
     * @param unknown_type $expTitle
     * @param unknown_type $expCellName
     * @param unknown_type $expTableData
     */
    public function exportExcel($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);

        vendor("PHPExcel.PHPExcel");

        $objPHPExcel = new \PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        // $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     *
     * 导出Excel
     */
    public function exp(){
        $xlsName  = "User";
        $xlsCell  = array(
            array('id','商品序号'),
            array('shop_title','商品名称'),
            array('shop_stock','库存'),
            array('shop_yprice','原价'),
            array('shop_price','现价'),
            array('shop_sales','销量'),
        );
        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');
            $where['id'] = array('in',$ids);
            $xlsData  = $this->shop_model->where($where)->Field('id,shop_title,shop_stock,shop_yprice,shop_price,shop_sales')->select();
            $this->exportExcel($xlsName,$xlsCell,$xlsData);
        }else{
            return false;
        }
    }
}